package com.pai4j.act.service;
import com.pai4j.act.repository.entity.ResourceBehaviorEntity;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;


/**
 *  双向（支持取消操作）互动服务: 点赞、关注、收藏、评论等
 *
 * @author: CYM-pai
 * @date: 2025/07/13 18:41
 **/
@Service
public class TwoWayResourceBehaviorService extends AbstractResourceBehaviorService {

    private static final String BEHAVIOR_ERROR_MSG = "%s失败";
    private static final String CANCEL_BEHAVIOR_ERROR_MSG = "取消%s失败";

    /**
     * 执行行为操作
     *
     * @param userId 用户ID
     * @param resourceType 资源类型
     * @param resourceId 资源ID
     * @return boolean 执行结果，false表示执行失败
     */
    @Override
    protected boolean doBehavior(String userId, String resourceType, Long resourceId) {
        // isBehavior 为true 表示已存在行为，则不允许再次执行行为
        boolean isBehavior = this.isBehavior(userId, resourceType, resourceId);
        // 验证用户行为是否合法，如果已存在行为则抛出异常
        Assert.isTrue(!isBehavior, String.format(BEHAVIOR_ERROR_MSG, super.behaviorTypeName));
        // 创建新的资源行为记录并保存
        ResourceBehaviorEntity resourceBehavior = new ResourceBehaviorEntity();
        resourceBehavior.setUserId(userId);
        resourceBehavior.setBehaviorType(super.behaviorType);
        resourceBehavior.setResourceType(resourceType);
        resourceBehavior.setResourceIndex(resourceId);
        resourceBehavior.setStatus(true);
        super.resourceBehaviorDAO.save(resourceBehavior);
        return true;
    }

    /**
     * 取消行为操作
     *
     * @param userId 用户ID
     * @param resourceType 资源类型
     * @param resourceId 资源ID
     * @return boolean 取消结果，true表示取消成功
     */
    @Override
    protected boolean doCancelBehavior(String userId, String resourceType, Long resourceId) {

        boolean isBehavior = this.isBehavior(userId, resourceType, resourceId);
        //  如果isBehavior为false 则表示用户没有行为，则不允许取消行为,报错.
        Assert.isTrue(isBehavior, String.format(CANCEL_BEHAVIOR_ERROR_MSG, super.behaviorTypeName));

        ResourceBehaviorEntity resourceBehavior =
                resourceBehaviorDAO.findByUserIdAndBehaviorTypeAndResourceTypeAndResourceIndexAndStatusTrue(
                userId, super.behaviorType, resourceType, resourceId);
        Assert.notNull(resourceBehavior, String.format(CANCEL_BEHAVIOR_ERROR_MSG, super.behaviorTypeName));
        // 互动已取消
        resourceBehavior.setStatus(false);
        super.resourceBehaviorDAO.save(resourceBehavior);
        return true;
    }
    

}
